# ~*~ coding: utf-8 ~*~
# auth: haochenxiao
import time,datetime,hashlib
from django.shortcuts import render
from django.template import RequestContext
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, View
from django.shortcuts import render_to_response,HttpResponse
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from alert.models import AlertHistory,LinkPerson,LinkGroup,AlertConfig
from devops.models import AutoReCovery,MonitorConfig
from alert.mailers import SendtestMail
from confs.Log import logger

api_key_record = {}

class AlertHistoryView(LoginRequiredMixin, TemplateView):
	template_name = 'alerthistory.html'

	def get(self, request):
		#print('role_id is ', request.session.role_id)
		user = request.user.username
		obj = AlertHistory.objects.all().order_by('-id')[:100]
		type_list = AlertHistory.type_list
		return render_to_response('alerthistory.html', locals())

class LinkPersonView(LoginRequiredMixin, TemplateView):
	template_name = 'linkperson.html'

	def get(self, request):
		user = request.user.username
		obj = LinkPerson.objects.all().order_by('-id')[:100]
		return render_to_response('linkperson.html', locals())

	def post(self,request):
		ret = {'status': 0}
		name = request.POST.get('name')
		mobile = request.POST.get('mobile')
		email = request.POST.get('email')
		dingding = request.POST.get('dingding')
		LinkPerson.objects.create(name=name,mobile=mobile,email=email,dingding=dingding)
		ret['msg'] = '联系人创建成功'
		return JsonResponse(ret)

class PersonEditView(LoginRequiredMixin, TemplateView):
	template_name = 'person_edit.html'

	def get(self, request):
		id = request.GET.get('id')
		pe_obj = LinkPerson.objects.get(id=id)
		return render_to_response('person_edit.html', locals())

	def post(self,request):
		id = request.POST.get('id')
		name = request.POST.get('name')
		email = request.POST.get('email')
		mobile = request.POST.get('mobile')
		dingding = request.POST.get('dingding')
		LinkPerson.objects.filter(id=id).update(name=name,email=email,mobile=mobile,dingding=dingding)
		return HttpResponseRedirect('/alert/alert_linkperson/')


class LinkPersonDeleteView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		linkperson_id = request.POST.get('linkperson_id')
		lp = LinkPerson.objects.get(id=linkperson_id)
		lp.delete()
		ret['msg'] = '联系人删除成功'
		ret['msg'] = '删除成功'
		return JsonResponse(ret)

class LinkGroupView(LoginRequiredMixin, TemplateView):
	template_name = 'linkgroup.html'

	def get(self, request):
		user = request.user.username
		obj_groups = LinkGroup.objects.all()
		obj_persons = LinkPerson.objects.all()
		#反查方法
		#a_id = LinkPerson.objects.get(id=6).group.name
		#lgroup = LinkGroup.objects.get(id=18)
		#mm = lgroup.linkgroup.all()
		return render_to_response('linkgroup.html', locals())

class LinkGroupCreateView(LoginRequiredMixin, TemplateView):
	template_name = 'linkgroup_create.html'

	def get(self, request):
		user = request.user.username
		obj_groups = LinkGroup.objects.all()
		obj_persons = LinkPerson.objects.all()
		return render_to_response('linkgroup_create.html', locals())

	def post(self,request):

		name = request.POST.get('name')
		dingurl = request.POST.get('dingurl')
		info = request.POST.get('info')
		memberslist = request.POST.getlist('members')
		lgp = LinkGroup.objects.create(name=name,dingurl=dingurl,info=info)

		#多对多添加
		for user_id in memberslist:
			lp = LinkPerson.objects.get(id=user_id)
			lgp.gl.add(lp)
		lgp.save()

		return HttpResponseRedirect('/alert/alert_linkgroup')


class LinkGroupEditView(LoginRequiredMixin, TemplateView):
	template_name = 'linkgroup_edit.html'

	def get(self, request):
		id = request.GET.get('id')
		obj_group = LinkGroup.objects.get(id=id)
		obj_persons = LinkPerson.objects.all()
		return render_to_response('linkgroup_edit.html', locals())

	def post(self,request):
		id = request.POST.get('id')
		print ('id is ',id)
		name = request.POST.get('name')
		dingurl = request.POST.get('dingurl')
		info = request.POST.get('info')
		memberslist = request.POST.getlist('members')

		LinkGroup.objects.filter(id=id).update(name=name,dingurl=dingurl,info=info)

		lgp = LinkGroup.objects.get(id=id)
		#lgp.gl.clear()
		print(memberslist)
		#多对多添加
		lp = LinkPerson.objects.filter(id__in = memberslist)
		lgp.gl.set(lp)
		lgp.save()

		return HttpResponseRedirect('/alert/alert_linkgroup')


class LinkGroupDeleteView(LoginRequiredMixin, TemplateView):

	def post(self,request):
		ret = {'status': 0}
		linkgroup_id = request.POST.get('linkgroup_id')
		lp = LinkGroup.objects.get(id=linkgroup_id)
		lp.delete()
		ret['msg'] = '联系人删除成功'
		ret['msg'] = '删除成功'
		return JsonResponse(ret)




class AttenTionConfigView(LoginRequiredMixin, TemplateView):
	template_name = 'attention_config.html'

	def get(self, request):
		objs = AlertConfig.objects.first()
		return render_to_response('attention_config.html', locals())

	def post(self,request):

		host = request.POST.get('host')
		email = request.POST.get('email')
		password = request.POST.get('password')
		port = request.POST.get('port')
		cname = request.POST.get('cname')
		apitoken = request.POST.get('apitoken')

		result = SendtestMail(host, email, password,cname,port)

		if result == 1:
			return HttpResponse('邮件配置不正确,请检查后重试')

		objs = AlertConfig.objects.first()
		if objs == None:
			AlertConfig.objects.create(host=host,email=email,password=password,port=port,cname=cname,apitoken=apitoken)
		else:
			objs.host = host if host != '' else print ('为空值,跳过')
			objs.email = email if email != '' else print ('为空值,跳过')
			objs.password = password if password != '' else print ('为空值,跳过')
			objs.port = port if port != '' else print ('为空值,跳过')
			objs.cname = cname if cname != '' else print ('为空值,跳过')
			objs.apitoken = apitoken if apitoken != '' else print ('为空值,跳过')
			objs.save()

		return HttpResponseRedirect('/alert/attentionconfig/')






def api_auth(func):

	def inner(request,*args,**kwargs):

		API_AUTH = AlertConfig.objects.first().apitoken
		client_md5_time_key = request.META.get('HTTP_OPENKEY')
		hao_key = request.META.get('HTTP_HAOKEY')
		client_md5_key, client_ctime = client_md5_time_key.split('|')

		client_ctime = float(client_ctime)
		server_time = time.time()

		# 第一关：时间关 10s内访问
		if server_time - client_ctime > 10:
			return HttpResponse('[第一关] 访问时间超时！')

		# 第二关：规则关 防止修改时间
		temp = "%s|%s" % (API_AUTH, client_ctime)
		m = hashlib.md5()
		m.update(bytes(temp, encoding='utf-8'))
		server_md5_key = m.hexdigest()
		if server_md5_key != client_md5_key:
			return HttpResponse('[第二关] 规则不正确')

		for k in list(api_key_record.keys()):
			v = api_key_record[k]
			if server_time > v:
				del api_key_record[k]

		# 第三关
		if client_md5_time_key in api_key_record:
			return HttpResponse('[第三关] 令牌已使用过')
		else:
			api_key_record[client_md5_time_key] = client_ctime + 10

		return func(request,*args,**kwargs)
	return inner


@api_auth
def APIOperation(request):
	if request.method == 'POST':
		name = request.POST.get('name')
		auto_status = request.POST.get('auto_status')

		try:
			arc = MonitorConfig.objects.get(name=name)
			arc.auto_status = auto_status
			arc.save()
			return HttpResponse('ok')
		except Exception as e:
			logger.info(e)
			print (e)
			return HttpResponse(e)


